package com.chuanyang.driverh.mainhome;


import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.overlay.PoiOverlay;
import com.chuanyang.driverh.BaseApplication;
import com.chuanyang.driverh.R;
import com.chuanyang.driverh.amap.AMapUtil;
import com.chuanyang.driverh.amap.MapUtils;
import com.chuanyang.driverh.base.BaseTitleActivity;
import com.chuanyang.driverh.base.OnCustomListener;
import com.chuanyang.driverh.mainhome.adapter.WaybilLocationAdapter;
import com.chuanyang.driverh.mainhome.fragment.WaybilListFragment;
import com.chuanyang.driverh.response2.ResultWaitTransDriver;
import com.chuanyang.driverh.responseresult.CurrentGpsData;
import com.chuanyang.driverh.responseresult.CurrentGpsResult;
import com.chuanyang.driverh.responseresult.LookWaybillData;
import com.chuanyang.driverh.responseresult.LookWaybillResult;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.StringUtil;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;


public class WaybilListActivity extends BaseTitleActivity {
    private LinearLayout ll_container;
    private RadioGroup rg_top;
    private ImageView iv_search_back;
    //    private int  listOrMap=1;//记录一下当前预选单列表的类型 1 list 2 map
    private WaybilListFragment listFragment ;
    //    private WaybilMapFragment mapFragment=new WaybilMapFragment();
    FragmentManager fm;
//    ResultWaitTransDriver.OutDataEntity.DataEntity data;

    private MapView mMapView = null;
    private AMap aMap;
    private PoiOverlay polyline;
    private LinearLayout ll_first_car_msg;
    private RelativeLayout rl_rotation_arrow;
    private ImageView iv_rotation_arrow;


//    private List<LookWaybillData.DataBean> wayBillEntityList = new ArrayList<>();


    private UiSettings mUiSettings;//定义一个UiSettings对象
    private ArrayList<MarkerOptions> markerGuideList = new ArrayList<>();
    private ArrayList<CurrentGpsData> billEntityList = new ArrayList<>();
    private MarkerOptions markerOptionsGuide;
    private LatLng guide;
    private int k = 0;
    private CurrentGpsData currentPosition;
    private LookWaybillData lookWaybillData;
    private LinearLayout rl_driver_msg;
    private int status;
    private boolean isReflesh;
    private ListView lv_waybil;

    LookWaybillResult waybilList;
    WaybilLocationAdapter adapter;

    ResultWaitTransDriver.OutDataEntity.DataEntity resultWaitTransEntity;
    public ResultWaitTransDriver.OutDataEntity.DataEntity getResultWaitTransEntity() {
        return resultWaitTransEntity;
    }

    //    private String begin = "";
//    private String end = "";
    //    private String orderId = "";

//    public String getBegin(){
//        return begin;
//    }
//    public String getEnd(){
//        return end;
//    }
//
//    public String getOrderId(){
//        return orderId;
//    }

    public void setData(LookWaybillResult result) {
        this.waybilList = result;
//        List<LookWaybillData.DataBean> ss = result.getData().getData();
        adapter = new WaybilLocationAdapter(activityContext);
        if (lv_waybil != null) {
            adapter.addAll(result.getData().getData());
            lv_waybil.setAdapter(adapter);

            adapter.setOnCustomListener(new OnCustomListener() {
                @Override
                public void onCustomerListener(View v, int position) {
                    try {
                        String carNum=waybilList.getData().getData().get(position).getPlateNumber();
                        for (int i=0;i<billEntityList.size();i++) {
                            if (carNum.equals(billEntityList.get(i).getPlateNumber())) {
                                AMapUtil.moveToLatLng(aMap,new LatLng(Double.parseDouble(billEntityList.get(i).getLast_lat()),Double.parseDouble(billEntityList.get(i).getLast_lon())),16);
                                break;
                            }
                            if (i==billEntityList.size()){
                                PrintUtil.toast(activityContext,"当前车辆无定位信息");
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            });
        }
    }

    public LookWaybillResult getData() {

        return waybilList;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMapView = (MapView) findViewById(R.id.map_order);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，实现地图生命周期管理
        mMapView.onCreate(savedInstanceState);
        //初始化地图变量
        if (aMap == null) {
            aMap = mMapView.getMap();
            setUpMap();
        }
    }


//    public ResultWaitTransDriver.OutDataEntity.DataEntity getData() {
//        return data;
//    }

    @Override
    protected int getContentResId() {
        return R.layout.home_act_waybil_list;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        hideTitleBar();
        iv_search_back = (ImageView) findViewById(R.id.iv_search_back);
        ll_container = (LinearLayout) findViewById(R.id.ll_container);
        rg_top = (RadioGroup) findViewById(R.id.rg_top);


        ll_first_car_msg = (LinearLayout) findViewById(R.id.ll_first_car_msg);
        rl_rotation_arrow = (RelativeLayout) findViewById(R.id.rl_rotation_arrow);
        iv_rotation_arrow = (ImageView) findViewById(R.id.iv_rotation_arrow);
        iv_rotation_arrow.setOnClickListener(this);


        rl_driver_msg = (LinearLayout) findViewById(R.id.rl_driver_msg);
        lv_waybil = (ListView) findViewById(R.id.lv_waybil);
        lv_waybil.setAdapter(adapter);
        ll_container.setVisibility(View.VISIBLE);
    }

    @Override
    protected void initData() {
//        data = (ResultWaitTransDriver.OutDataEntity.DataEntity) getIntent().getSerializableExtra("data");
//        orderId = data.getOrderId() + "";
//        orderNo = data.getOrderNo() + "";

//        orderId=getIntent().getStringExtra("data");
//        begin=getIntent().getStringExtra("begin");
//        end=getIntent().getStringExtra("end");

        resultWaitTransEntity=( ResultWaitTransDriver.OutDataEntity.DataEntity)getIntent().getSerializableExtra("data");


        listFragment = new WaybilListFragment();

        fm = getSupportFragmentManager();
        if (ll_container.getChildCount() > 0) ll_container.removeAllViews();
        fm.beginTransaction().add(R.id.ll_container, listFragment).commit();
//                getWybill(orderId, orderNo, "1", "200");//之后要有分页
        // getWybill("91", "D01121400000013", "1", "2");//之后要有分页

        if (resultWaitTransEntity!=null && resultWaitTransEntity.getOrderId()!=0)
        GetCarCurrentStatusByOrderId(resultWaitTransEntity.getOrderId()+"");
//        GetCarCurrentStatusByOrderId(orderId);
        // GetCarCurrentStatusByOrderId("91");

    }

    private void setUpMap() {
        mUiSettings = aMap.getUiSettings();//实例化UiSettings类
        mUiSettings.setScaleControlsEnabled(true);//显示比例尺控件
        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory
                .fromResource(R.mipmap.location_marker));// 设置小蓝点的图标
        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        //myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
        //myLocationStyle.anchor(int,int)//设置小蓝点的锚点
        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);


        try {
            if (BaseApplication.getInstance().getLocationEntity()!=null ){
                AMapUtil.moveToLatLng(aMap,new LatLng(BaseApplication.getInstance().getLocationEntity().getLatitude(),BaseApplication.getInstance().getLocationEntity().getLongitude()),14);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void initListener() {
        iv_search_back.setOnClickListener(this);
        rg_top.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_top1:
                        ll_container.setVisibility(View.VISIBLE);
                        break;
                    case R.id.rb_top2:
                        ll_container.setVisibility(View.GONE);
                        break;
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_search_back:
                finish();
                break;
            case R.id.iv_rotation_arrow:
                //判断ll_first_car_msg是隐藏还是显示；
                if (ll_first_car_msg.getVisibility() == View.GONE) {
                    ll_first_car_msg.setVisibility(View.VISIBLE);
                    iv_rotation_arrow.setRotation(90);
                } else if (ll_first_car_msg.getVisibility() == View.VISIBLE) {
                    ll_first_car_msg.setVisibility(View.GONE);
                    iv_rotation_arrow.setRotation(-90);
                }
                break;


        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
        mMapView.onSaveInstanceState(outState);
    }


    /**
     * 获取车辆的所有的GPS定位，
     *
     * @param orderId
     */
    private void GetCarCurrentStatusByOrderId(String orderId) {
        DialogUtil.showLoadingDialog(activityContext, "加载中...");
        Map<String, String> params = new HashMap<String, String>();
        params.put("orderId", orderId);
        MyHttpUtil.GetCarCurrentStatusByOrderId(activityContext, params, new MyCallback<CurrentGpsResult>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(CurrentGpsResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    billEntityList.addAll(result.getData());
                    //设置标记点
                    aMap.clear();
                    for (int i = 0; i < billEntityList.size(); i++) {
                        //MapUtils.getGdLatLng转换为高德地图坐标
                        //以前根据carId判断是手机定位还是设备定位，现在根据id判断，有id这个字段就是手机定位。
//                        if (StringUtil.isBlank(billEntityList.get(i).getCarID())){
                        if (billEntityList.get(i).getId()>0){
                            guide=new LatLng(Double.parseDouble(billEntityList.get(i).getLast_lat()),Double.parseDouble(billEntityList.get(i).getLast_lon()));
                        }else {
                            guide = MapUtils.getGdLatLng(activityContext, new LatLng(Float.parseFloat(billEntityList.get(i).getLast_lat()),
                                    Float.parseFloat(billEntityList.get(i).getLast_lon())));
                        }
                        markerOptionsGuide = new MarkerOptions();
                        //  markerOptionsGuide.position(guide).title(billEntityList.get(i).getCarMark());
                        markerOptionsGuide.position(guide);
                        if (!StringUtil.isBlank(billEntityList.get(i).getPlateNumber()))    markerOptionsGuide.title(billEntityList.get(i).getPlateNumber());
                        if (!StringUtil.isBlank(billEntityList.get(i).getLocation()))      markerOptionsGuide.snippet(billEntityList.get(i).getLocation());
                        markerOptionsGuide.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                                .decodeResource(getResources(), R.mipmap.place)));
//                                .decodeResource(getResources(), R.mipmap.location)));
//                        markerOptionsGuide.title(billEntityList.get(i).getCarMark() + "");
                        markerGuideList.add(markerOptionsGuide);
                    }
                    aMap.addMarkers(markerGuideList, true);
                } else {
//                    PrintUtil.toast(activityContext, result.getMsg());
                }
            }
        });
    }



 /*   private void showMark(LookWaybillData.DataBean dataBean) {
        //MapUtils.getGdLatLng转换为高德地图坐标
        for (int i = 0; i < billEntityList.size(); i++)
        {
            if (billEntityList.get(i).getCarMark().equals(dataBean.getPlateNumber())) {
                currentPosition = billEntityList.get(i);
            }

        }
        if(currentPosition!=null) {
            guide = MapUtils.getGdLatLng(activityContext, new LatLng(Float.parseFloat(currentPosition.getLast_lat()),
                    Float.parseFloat(currentPosition.getLast_lon())));
            markerOptionsGuide = new MarkerOptions();
            //  markerOptionsGuide.position(guide).title(billEntityList.get(i).getCarMark());
            markerOptionsGuide.position(guide);
//                        markerOptionsGuide.title(billEntityList.get(i).getFirmName());
//                        markerOptionsGuide.snippet(billEntityList.get(i).getAddress());
            markerOptionsGuide.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                    .decodeResource(getResources(), R.mipmap.location)));
            markerOptionsGuide.title(currentPosition.getCarMark()+"");
//        markerGuideList.add(markerOptionsGuide);
            markerOptionsGuide.title(dataBean.getPlateNumber());
            aMap.addMarker(markerOptionsGuide);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(guide));
        }
    }*/


}
